import { createRouter, createWebHistory } from "vue-router";
import { getToken, isValidToken } from "@/utils/auth";
import { useUserStore } from "@/stores/user";
import { ElMessage } from "element-plus";
import { refresh, logout } from "@/api/auth";
import { setToken } from "@/utils/auth";

const routes = [
  {
    path: "/login",
    name: "Login",
    component: () => import("../views/auth/Login.vue"),
    meta: { title: "用户登录", requiresAuth: false },
  },
  {
    path: "/register",
    name: "Register",
    component: () => import("../views/auth/Register.vue"),
    meta: { title: "用户注册", requiresAuth: false },
  },
  {
    path: "/",
    component: () => import("../views/layout/AdminLayout.vue"),
    redirect: "/dashboard",
    meta: { title: "首页", requiresAuth: true },
    children: [
      {
        path: "dashboard",
        name: "Dashboard",
        component: () => import("../views/dashboard/index.vue"),
        meta: { title: "控制台", icon: "dashboard", requiresAuth: true },
      },
      {
        path: "customer",
        name: "Customer",
        component: () => import("../components/layout/MainContent.vue"),
        redirect: "/customer/list",
        meta: { title: "客户管理", icon: "user", requiresAuth: true },
        children: [
          {
            path: "list",
            name: "CustomerList",
            component: () => import("../views/customer/list.vue"),
            meta: { title: "客户列表", icon: "list", requiresAuth: true },
          },
          {
            path: "sales/opportunities",
            name: "salesOpportunities",
            component: () => import("../views/customer/salesOpportunities.vue"),
            meta: { title: "销售过程", icon: "Bell", requiresAuth: true },
          },
        ],
      },
      {
        path: "order",
        name: "Order",
        component: () => import("../components/layout/MainContent.vue"),
        redirect: "/order/list",
        meta: { title: "订单管理", icon: "Tickets", requiresAuth: true },
        children: [
          {
            path: "list",
            name: "OrderList",
            component: () => import("../views/order/list.vue"),
            meta: { title: "订单列表", icon: "List", requiresAuth: true },
          },
        ],
      },
      {
        path: "after-sales",
        name: "AfterSales",
        component: () => import("../components/layout/MainContent.vue"),
        redirect: "/after-sales/records",
        meta: { title: "售后服务", icon: "Service", requiresAuth: true },
        children: [
          {
            path: "records",
            name: "Records",
            component: () => import("../views/aftersales/recordList.vue"),
            meta: { title: "服务记录", icon: "Notebook", requiresAuth: true },
          },
          {
            path: "complaint",
            name: "Complaint",
            component: () => import("../views/complaint/list.vue"),
            meta: { title: "投诉处理", icon: "ChatLineRound", requiresAuth: true },
          },
        ],
      },
      {
        path: "system",
        name: "System",
        component: () => import("../components/layout/MainContent.vue"),
        redirect: "/system/menuList",
        meta: { title: "系统管理", icon: "Setting", requiresAuth: true },
        children: [
          {
            path: "menuList",
            name: "MenuList",
            component: () => import("../views/system/MenuList.vue"),
            meta: { title: "菜单列表", icon: "Menu", requiresAuth: true },
          },
          {
            path: "roleList",
            name: "RoleList",
            component: () => import("../views/system/RoleList.vue"),
            meta: { title: "角色管理", icon: "UserFilled", requiresAuth: true },
          },
          {
            path: "userList",
            name: "UserList",
            component: () => import("../views/system/UserList.vue"),
            meta: { title: "用户管理", icon: "User", requiresAuth: true },
          },
        ],
      },
      {
        path: "/product",
        name: "Product",
        component: () => import("../components/layout/MainContent.vue"),
        redirect: "/product/list",
        meta: {
          title: "商品管理",
          icon: "ShoppingBag",
          requiresAuth: true,
        },
        children: [
          {
            path: "list",
            name: "ProductList",
            component: () => import("@/views/product/list/index.vue"),
            meta: {
              title: "商品列表",
              icon: "List",
            },
          },
          {
            path: "category",
            name: "ProductCategory",
            component: () => import("@/views/product/category/index.vue"),
            meta: {
              title: "商品分类",
              icon: "Menu",
            },
          },
          {
            path: "purchase",
            name: "ProductPurchase",
            component: () => import("@/views/product/purchase/index.vue"),
            meta: {
              title: "采购清单",
              icon: "List",
            },
          },
        ],
      },
      {
        path: "user",
        name: "UserCenter",
        component: () => import("../components/layout/MainContent.vue"),
        redirect: "/user/profile",
        meta: { title: "个人中心", icon: "User", requiresAuth: true },
        children: [
          {
            path: "profile",
            name: "UserProfile",
            component: () => import("../views/user/Profile.vue"),
            meta: { title: "个人信息", icon: "UserFilled", requiresAuth: true },
          },
          {
            path: "change-password",
            name: "ChangePassword",
            component: () => import("../views/user/ChangePassword.vue"),
            meta: { title: "修改密码", icon: "Lock", requiresAuth: true },
          },
        ],
      },
      {
        path: "warehouse",
        name: "Warehouse",
        component: () => import("../components/layout/MainContent.vue"),
        redirect: "/warehouse/list",
        meta: { title: "仓库管理", icon: "Box", requiresAuth: true },
        children: [
          {
            path: "list",
            name: "WarehouseList",
            component: () => import("../views/warehouse/index.vue"),
            meta: { title: "仓库列表", icon: "List", requiresAuth: true },
          },
        ],
      },
    ],
  },
  // 404 页面
  {
    path: "/:pathMatch(.*)*",
    name: "NotFound",
    component: () => import("../views/404.vue"),
    meta: { requiresAuth: false },
  },
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});

// 路由守卫
router.beforeEach(async (to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - ERP系统` : "ERP系统";

  // 如果路由不需要认证，直接通过
  if (to.meta.requiresAuth === false) {
    next();
    return;
  }

  // 获取token并检查有效性
  const token = getToken();
  if (!token) {
    console.log("token无效");
    console.log(to.path);
    if (to.path !== "/login") {
      const res = await refresh();
      if (res.success) {
        // token刷新成功，重新获取token
        const token = res.data;
        setToken(token);
        next();
        return;
      }
    }
    // 如果token无效，清除用户状态
    const userStore = useUserStore();
    userStore.logout(); // logout中已包含removeToken()
    // 发送请求退出登录
    logout();
    // 重定向到登录页
    ElMessage.warning("请先登录");
    next("/login");
    return;
  }

  // token有效，允许访问
  next();
});

console.log(process.env.BASE_URL);

export default router;
